package de.axone.client;

import java.util.HashMap;

import de.axone.wash.Wash;
import de.axone.wash.Wash.WashException;
import de.axone.wash.client.WashClient;
import de.axone.wash.client.WashClient.ClientException;

public class WashProxy {

	protected static WashProxy instance = null;
	private WashClient wc = null;
	private HashMap<String,CallResult> callMap = new HashMap<String, CallResult>();
	private long runTime = 36000000;
	
	public static WashProxy getInstance( ){
	    if ( WashProxy.instance == null ) {
	    	//System.setProperty("javax.net.ssl.trustStore", XXXX );
			//System.setProperty("javax.net.ssl.trustStorePassword", "xxxx");
	    	WashProxy.instance = new WashProxy( );
	    }
	    return WashProxy.instance;
	}

	public WashClient getWashClient() {
		return wc;
	}

	public void setWashClient(WashClient wc) {
		this.wc = wc;
	}
	
	public Wash call( String service, String operation, Wash request ) throws ClientException, WashException{
		String hash = service+operation+request.serialize();
		if( callMap.containsKey( hash ) ){
			if( (System.currentTimeMillis()-callMap.get( hash ).time) >= runTime ){
				Wash res = wc.call( service, operation, request );
				CallResult cr = new CallResult();
				cr.result = res;
				cr.time = System.currentTimeMillis();
				callMap.put( hash, cr );
				return res;
			}else{
				return callMap.get( hash ).result;
			}
			
		}else{
			Wash res = wc.call( service, operation, request );
			CallResult cr = new CallResult();
			cr.result = res;
			cr.time = System.currentTimeMillis();
			callMap.put( hash, cr );
			return res;
		}
	}
	
	class CallResult{
		
		long time;
		Wash result;
	}

	public long getRunTime() {
		return runTime;
	}

	public void setRunTime(long runTime) {
		this.runTime = runTime;
	}
}
